<script lang="ts" setup>
import { i18n } from "@/locales";
import type { NodeViewProps } from "@/tiptap/vue-3";
import { NodeViewWrapper } from "@/tiptap/vue-3";
import { isAllowedUri } from "@/utils/is-allowed-uri";
import { computed, onMounted, ref } from "vue";

const props = defineProps<NodeViewProps>();

const src = computed({
  get: () => {
    return props.node?.attrs.src;
  },
  set: (src: string) => {
    if (!src || !isAllowedUri(src)) {
      return;
    }
    props.updateAttributes({ src: src });
  },
});

const frameborder = computed(() => {
  return props.node.attrs.frameborder;
});

function handleSetFocus() {
  props.editor.commands.setNodeSelection(props.getPos() || 0);
}
const inputRef = ref();

onMounted(() => {
  if (!src.value) {
    inputRef.value.focus();
  }
});
</script>

<template>
  <node-view-wrapper as="div" class="iframe-wrapper">
    <div
      class="iframe-container"
      :style="{
        width: node.attrs.width,
      }"
    >
      <div v-if="!src" class="iframe-input-wrapper">
        <input
          ref="inputRef"
          v-model.lazy="src"
          class="iframe-input"
          :placeholder="i18n.global.t('editor.common.placeholder.link_input')"
          tabindex="-1"
          @focus="handleSetFocus"
        />
      </div>
      <iframe
        v-else
        class="iframe-element"
        :class="{
          'has-border': frameborder === '1',
        }"
        :src="node!.attrs.src"
        :width="node.attrs.width"
        :height="node.attrs.height"
        scrolling="yes"
        :frameborder="frameborder"
        framespacing="0"
        allowfullscreen="true"
        @mouseenter="handleSetFocus"
      ></iframe>
    </div>
  </node-view-wrapper>
</template>

<style lang="scss" scoped>
.iframe-wrapper {
  display: inline-block;
  width: 100%;
}

.iframe-container {
  position: relative;
  display: inline-block;
  height: 100%;
  max-width: 100%;
  overflow: hidden;
  text-align: center;
  transition: all 0.2s;
}

.iframe-input-wrapper {
  padding: 0.375rem; // p-1.5
}

.iframe-input {
  display: block;
  width: 100%;
  border-radius: 0.375rem; // rounded-md
  border: 1px solid var(--editor-input-border);
  background-color: var(--editor-input-bg);
  padding: 0.375rem 0.5rem; // px-2 py-1.5
  font-size: 0.875rem; // text-sm
  color: var(--editor-input-text);

  &:focus {
    border-color: var(--editor-input-focus-border);
    outline: none;
    box-shadow: 0 0 0 1px var(--editor-input-focus-border);
  }
}

.iframe-element {
  border-radius: 0.375rem; // rounded-md

  &.has-border {
    border-width: 2px; // border-2
  }
}
</style>
